import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, InputNumber, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Option } = Select;

// API 基础URL
const API_BASE_URL = 'http://localhost:3001';

const MenuManagement = () => {
  const [menuList, setMenuList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加菜单');
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState(null);

  // 获取菜单列表
  const fetchMenuList = async () => {
    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/menus`);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();
      if (data.code === 200) {
        const menuData = data.data.map(item => ({ ...item, key: item.id }));
        setMenuList(menuData);
      } else {
        throw new Error(data.message || '获取菜单列表失败');
      }
    } catch (error) {
      message.error('获取菜单列表失败: ' + error.message);
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMenuList();
  }, []);

  // 添加或更新菜单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentId) {
        // 更新菜单
        const response = await fetch(`${API_BASE_URL}/api/menus/${currentId}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(values)
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.code === 200) {
          message.success('更新成功');
          setModalVisible(false);
          fetchMenuList();
        } else {
          throw new Error(data.message || '更新失败');
        }
      } else {
        // 添加菜单
        const response = await fetch(`${API_BASE_URL}/api/menus`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(values)
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.code === 200) {
          message.success('添加成功');
          setModalVisible(false);
          fetchMenuList();
        } else {
          throw new Error(data.message || '添加失败');
        }
      }
    } catch (error) {
      message.error('操作失败: ' + error.message);
      console.error('提交表单失败:', error);
    }
  };

  // 删除菜单
  const handleDelete = async (id) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/menus/${id}`, {
        method: 'DELETE'
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();
      if (data.code === 200) {
        message.success('删除成功');
        fetchMenuList();
      } else {
        throw new Error(data.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败: ' + error.message);
      console.error(error);
    }
  };

  // 打开添加菜单模态框
  const showAddModal = () => {
    setModalTitle('添加菜单');
    setCurrentId(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 打开编辑菜单模态框
  const showEditModal = (record) => {
    setModalTitle('编辑菜单');
    setCurrentId(record.id);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path'
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon'
    },
    {
      title: '父级ID',
      dataIndex: 'parentId',
      key: 'parentId'
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span>{status === 1 ? '启用' : '禁用'}</span>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此菜单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={showAddModal}
        >
          添加菜单
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={menuList} 
        loading={loading}
        pagination={{ pageSize: 10 }}
        rowKey="id"
      />
      
      <Modal
        title={modalTitle}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ parentId: 0, order: 1, status: 1 }}
        >
          <Form.Item
            name="name"
            label="菜单名称"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          
          <Form.Item
            name="path"
            label="路径"
            rules={[{ required: true, message: '请输入路径' }]}
          >
            <Input placeholder="请输入路径" />
          </Form.Item>
          
          <Form.Item
            name="icon"
            label="图标"
          >
            <Input placeholder="请输入图标名称" />
          </Form.Item>
          
          <Form.Item
            name="parentId"
            label="父级菜单"
          >
            <Select placeholder="请选择父级菜单">
              <Option value={0}>顶级菜单</Option>
              {menuList
                .filter(item => item.parentId === 0)
                .map(item => (
                  <Option key={item.id} value={item.id}>{item.name}</Option>
                ))
              }
            </Select>
          </Form.Item>
          
          <Form.Item
            name="order"
            label="排序"
          >
            <InputNumber min={1} />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;